package com.ruoyi.web.controller.jiuyezu;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.jiuyezu.domain.Registers;
import com.ruoyi.jiuyezu.service.IRegistersService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import static com.ruoyi.common.utils.PageUtils.startPage;

/**
 * 就业组抽背登记记录Controller
 *
 * @author wyj
 * @date 2024-07-23
 */
@RestController
@RequestMapping("/jiuyezu/registers")
public class RegistersController extends BaseController {
    @Autowired
    private IRegistersService registersService;

    @PostMapping("/upload")
    public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("上传文件为空");
        }

        try {
            StringBuilder fileContent = new StringBuilder();
            try (InputStream inputStream = file.getInputStream();
                 BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    fileContent.append(line).append("\n");
                }
            }

            List<Registers> registersList = parseText(fileContent.toString());

            registersService.insertRegistersList(registersList);

            return ResponseEntity.ok(registersList);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件上传失败");
        }
    }

    private List<Registers> parseText(String text) {
        List<Registers> registersList = new ArrayList<>();
        String[] lines = text.split("\\n");
        Date currentDate = null;
        String currentClassId = null;
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat inputDateFormat = new SimpleDateFormat("M.dd");
        SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd");

        for (int i = 0; i < lines.length; i++) {
            String line = lines[i].trim();
            if (line.matches("\\d{1,2}\\.\\d{1,2}")) {//匹配时间
                try {
                    Date parsedDate = inputDateFormat.parse(line);
                    calendar.setTime(parsedDate);
                    calendar.set(Calendar.YEAR, Calendar.getInstance().get(Calendar.YEAR));  // Assume current year
                    currentDate = calendar.getTime();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (line.matches("\\d+|[tT]\\d+")) {//匹配班级
                if (line.startsWith("t") || line.startsWith("T")) {
                    currentClassId = line.toUpperCase();
                } else if (line.matches("^\\d+$")) {
                    currentClassId = "T" + line;
                }

            } else if (line.contains("已抄完") || line.contains("ok") || line.matches(".*\\S.*")) {
                String name = line.split(" ")[0];
                boolean isCompleted = line.contains("已抄完") || line.contains("ok");
                List<String> wrongQuestionsList = new ArrayList<>();
                while (++i < lines.length && lines[i].trim().matches(".*\\S.*") && !lines[i].matches("\\d+|T\\d+|\\d{1,2}\\.\\d{1,2}")) {
                    wrongQuestionsList.add(lines[i].trim());
                }
                if (line.contains("ok")) wrongQuestionsList.add("全对");

                i--;  // Step back to process the next class or date
                String wrongQuestions = String.join(";", wrongQuestionsList);
                Registers register = new Registers();
                register.setDate(currentDate);
                register.setClasses(currentClassId);
                register.setName(name);
                register.setIsCompleted(isCompleted ? 1 : 0);
                register.setWrongQuestions(wrongQuestions);
                register.setFileUploadTxt("");  // Assuming this field is handled separately
                register.setFileDownloadExcel("");  // Assuming this field is handled separately
                registersList.add(register);
            }
        }
        return registersList;
    }


    /**
     * 查询就业组抽背登记记录列表
     */
    @PreAuthorize("@ss.hasPermi('jiuyezu:registers:list')")
    @GetMapping("/list")
    public TableDataInfo list(Registers registers) {
        startPage();
        List<Registers> list = registersService.selectRegistersList(registers);
        return getDataTable(list);
    }

    /**
     * 导出就业组抽背登记记录列表
     */
    @PreAuthorize("@ss.hasPermi('jiuyezu:registers:export')")
    @Log(title = "就业组抽背登记记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Registers registers) {
        List<Registers> list = registersService.selectRegistersList(registers);
        ExcelUtil<Registers> util = new ExcelUtil<Registers>(Registers.class);
        util.exportExcel(response, list, "就业组抽背登记记录数据");
    }

    /**
     * 获取就业组抽背登记记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('jiuyezu:registers:query')")
    @GetMapping(value = "/{registerId}")
    public AjaxResult getInfo(@PathVariable("registerId") Long registerId) {
        return success(registersService.selectRegistersByRegisterId(registerId));
    }

    /**
     * 新增就业组抽背登记记录
     */
    @PreAuthorize("@ss.hasPermi('jiuyezu:registers:add')")
    @Log(title = "就业组抽背登记记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Registers registers) {
        return toAjax(registersService.insertRegisters(registers));
    }

    /**
     * 修改就业组抽背登记记录
     */
    @PreAuthorize("@ss.hasPermi('jiuyezu:registers:edit')")
    @Log(title = "就业组抽背登记记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Registers registers) {
        return toAjax(registersService.updateRegisters(registers));
    }

    /**
     * 删除就业组抽背登记记录
     */
    @PreAuthorize("@ss.hasPermi('jiuyezu:registers:remove')")
    @Log(title = "就业组抽背登记记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{registerIds}")
    public AjaxResult remove(@PathVariable Long[] registerIds) {
        return toAjax(registersService.deleteRegistersByRegisterIds(registerIds));
    }
}
